package com.qb.hotelTV.repository;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qb.hotelTV.Http.BackstageHttp;
import com.qb.hotelTV.Model.VideoModel;
import com.qb.hotelTV.Model.ApkModel;
import com.qb.hotelTV.Model.HotelMessageModel;
import com.qb.hotelTV.Model.RoomMessageModel;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * TV数据仓库类
 * 统一管理数据源：网络请求、本地缓存、SharedPreferences
 */
public class TvRepository {
    private static final String TAG = "TvRepository";
    private static final String PREFS_NAME = "HotelTV";
    private static final String KEY_SERVER_ADDRESS = "server_address";
    private static final String KEY_ROOM_NUMBER = "room_number";
    private static final String KEY_TENANT = "tenant";
    private static final String KEY_CHANNEL_CACHE = "channel_cache";
    private static final long CACHE_EXPIRE_TIME = TimeUnit.HOURS.toMillis(1); // 1小时缓存
    
    private Context context;
    private SharedPreferences sharedPreferences;
    private Gson gson;
    private BackstageHttp backstageHttp;
    
    // 单例模式
    private static volatile TvRepository instance;
    
    private TvRepository(Context context) {
        this.context = context.getApplicationContext();
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
        this.backstageHttp = BackstageHttp.getInstance();
    }
    
    public static TvRepository getInstance(Context context) {
        if (instance == null) {
            synchronized (TvRepository.class) {
                if (instance == null) {
                    instance = new TvRepository(context);
                }
            }
        }
        return instance;
    }
    
    /**
     * 获取TV频道列表
     * 优先使用缓存，缓存过期则请求网络
     */
    public Single<ArrayList<VideoModel>> getTvChannels() {
        return Single.fromCallable(() -> {
            // 检查缓存
            String cachedData = sharedPreferences.getString(KEY_CHANNEL_CACHE, "");
            long cacheTime = sharedPreferences.getLong(KEY_CHANNEL_CACHE + "_time", 0);
            
            if (!cachedData.isEmpty() && (System.currentTimeMillis() - cacheTime) < CACHE_EXPIRE_TIME) {
                Log.d(TAG, "使用缓存的频道数据");
                return gson.fromJson(cachedData, new TypeToken<ArrayList<VideoModel>>(){}.getType());
            }
            
            // 缓存过期或不存在，请求网络
            return fetchTvChannelsFromNetwork();
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
    }
    
    /**
     * 从网络获取频道数据
     */
    private ArrayList<VideoModel> fetchTvChannelsFromNetwork() {
        String serverAddress = getServerAddress();
        String tenant = getTenant();
        
        if (serverAddress.isEmpty() || tenant.isEmpty()) {
            Log.w(TAG, "服务器地址或租户信息为空");
            return new ArrayList<>();
        }
        
        return Single.<ArrayList<VideoModel>>create(emitter -> {
            backstageHttp.getTvChannel(serverAddress, tenant, new BackstageHttp.TvChannelCallback() {
                @Override
                public void onTvChannelResponse(ArrayList<VideoModel> videoModels) {
                    // 缓存数据
                    cacheChannelData(videoModels);
                    emitter.onSuccess(videoModels);
                }
                
                @Override
                public void onTvChannelFailure(int code, String msg) {
                    emitter.onError(new Exception(msg));
                }
            });
        })
        .subscribeOn(Schedulers.io())
        .blockingGet();
    }
    
    /**
     * 缓存频道数据
     */
    private void cacheChannelData(ArrayList<VideoModel> channels) {
        String jsonData = gson.toJson(channels);
        sharedPreferences.edit()
                .putString(KEY_CHANNEL_CACHE, jsonData)
                .putLong(KEY_CHANNEL_CACHE + "_time", System.currentTimeMillis())
                .apply();
        Log.d(TAG, "频道数据已缓存");
    }
    
    /**
     * 获取房间信息
     */
    public Single<RoomMessageModel> getRoomMessage() {
        return Single.create(emitter -> {
            String serverAddress = getServerAddress();
            String roomNumber = getRoomNumber();
            String tenant = getTenant();
            
            if (serverAddress.isEmpty() || roomNumber.isEmpty() || tenant.isEmpty()) {
                emitter.onError(new Exception("配置信息不完整"));
                return;
            }
            
            backstageHttp.getRoomMessage(serverAddress, roomNumber, tenant, 
                new BackstageHttp.RoomMessageCallback() {
                    @Override
                    public void onRoomMessageResponse(int id, String roomName, String wifiPassword, String frontDeskPhone) {
                        RoomMessageModel roomMessage = new RoomMessageModel();
                        roomMessage.setId(id);
                        roomMessage.setRoomName(roomName);
                        roomMessage.setWifiPassword(wifiPassword);
                        roomMessage.setFrontDeskPhone(frontDeskPhone);
                        emitter.onSuccess(roomMessage);
                    }
                    
                    @Override
                    public void onRoomMessageFailure(int code, String msg) {
                        emitter.onError(new Exception(msg));
                    }
                });
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
    }
    
    /**
     * 获取应用列表
     */
    public Single<ArrayList<ApkModel>> getApkList() {
        return Single.create(emitter -> {
            String serverAddress = getServerAddress();
            String tenant = getTenant();
            
            backstageHttp.getApkList(serverAddress, tenant, new BackstageHttp.ApkCallback() {
                @Override
                public void onApkResponse(ArrayList<ApkModel> apkModelArrayList) {
                    emitter.onSuccess(apkModelArrayList);
                }
                
                @Override
                public void onApkFailure(int code, String msg) {
                    emitter.onError(new Exception(msg));
                }
            });
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
    }
    
    // 配置管理方法
    public String getServerAddress() {
        return sharedPreferences.getString(KEY_SERVER_ADDRESS, "");
    }
    
    public String getRoomNumber() {
        return sharedPreferences.getString(KEY_ROOM_NUMBER, "");
    }
    
    public String getTenant() {
        return sharedPreferences.getString(KEY_TENANT, "");
    }
    
    public void saveConfiguration(String serverAddress, String roomNumber, String tenant) {
        sharedPreferences.edit()
                .putString(KEY_SERVER_ADDRESS, serverAddress)
                .putString(KEY_ROOM_NUMBER, roomNumber)
                .putString(KEY_TENANT, tenant)
                .putBoolean("isFirstRun", false)
                .apply();
        
        // 清除旧缓存
        clearCache();
    }
    
    public boolean isFirstRun() {
        return sharedPreferences.getBoolean("isFirstRun", true);
    }
    
    /**
     * 清除所有缓存
     */
    public void clearCache() {
        sharedPreferences.edit()
                .remove(KEY_CHANNEL_CACHE)
                .remove(KEY_CHANNEL_CACHE + "_time")
                .apply();
        Log.d(TAG, "缓存已清除");
    }
    
    /**
     * 刷新频道数据
     */
    public Single<ArrayList<VideoModel>> refreshChannels() {
        clearCache();
        return getTvChannels();
    }
} 